public class HashBuck {
    static class Node{
        public int key;
        public int val;
        public Node next;
        public Node(int key,int val){
            this.key = key;
            this.val = val;
        }
    }
    public Node[] array;
    public int usedSize;
    public double loadFactor = 0.75;
    public HashBuck(){
        array = new Node[10];
    }

    public void put(int key,int val){
        int index = key % array.length;
        Node cur = array[index];
        //先找是否有相同的key，如果有则更新val
        while(cur != null){
            if(cur.key == key){
                cur.val = val;
                return;
            }
            cur = cur.next;
        }
        //走完整个链表，进行头插
        Node newNode = new Node(key,val);
        newNode.next = array[index];
        array[index] = newNode;
        usedSize++;
        //扩容
        if(loadFactorCount() >= loadFactor){
            resize();
        }
    }
    private double loadFactorCount(){
        return usedSize*1.0 / array.length;
    }
    private void resize(){
        //每个数组下标的元素中，每个链表节点元素都要重新哈希
        Node[] newArray = new Node[2*array.length];
        for(int i = 0;i<array.length;i++){
            Node cur = array[i];
            while(cur != null){
                int newIndex = cur.key % newArray.length;
                Node curN = cur.next;
                cur.next = newArray[newIndex];
                newArray[newIndex] = cur;
                cur = curN;
            }
        }
        array = newArray;
    }

    public int get(int key){
        int index = key % array.length;
        Node cur = array[index];
        while(cur != null){
            if(cur.key == key){
                return cur.val;
            }
            cur = cur.next;
        }
        return -1;
    }
}
